package com.eve.chatsocket.hander;

import com.eve.chatsocket.constn.ChatConst;
import com.eve.chatsocket.entity.EventVo;
import com.eve.chatsocket.entity.Payload;
import com.eve.chatsocket.entity.ResponseData;
import com.eve.chatsocket.event.MessageEvent;
import com.eve.chatsocket.okhttp3.OkhttpListener;
import com.eve.chatsocket.utils.ChatUtils;
import com.eve.chatsocket.utils.WebSocketManager;
import com.eve.chatsocket.utils.WebSocketSessionManager;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import jakarta.annotation.PostConstruct;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import static com.eve.chatsocket.constn.ChatConst.json;
import static com.eve.chatsocket.utils.ChatUtils.getAuthorizationUrl;

@Component
@Slf4j
public class Myhandler extends AbstractWebSocketHandler {

    @Autowired
    private OkhttpListener okhttpListener;
    public String url = "";
    @PostConstruct
    public void initsocket() throws Exception {
        String authUrl = getAuthorizationUrl(ChatConst.hostUrl,ChatConst.APIKEY,ChatConst.APISecret);
        url = authUrl.replace("https://","wss://").replace("http://","ws://");
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("建立链接");
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        super.handleMessage(session, message);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        WebSocketSessionManager.add(session.getId(), session);
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).build();
        WebSocket webSocket = okHttpClient.newWebSocket(request, okhttpListener);
        WebSocketManager.add(session.getId(),webSocket);
        //客户端传来的文本消息
        String payload = message.getPayload();
        log.info("获取发送的文本消息为：{}",payload);
        JsonObject jsonObject = ChatUtils.getJsonObject(payload);
        webSocket.send(jsonObject.toString());
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        super.handleBinaryMessage(session, message);
    }

    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        super.handlePongMessage(session, message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //super.afterConnectionClosed(session, status);
        log.info("断开链接");
        WebSocketSessionManager.removeAndClose(session.getId());
        WebSocketManager.removeAndClose(session.getId());
    }

    @Override
    public boolean supportsPartialMessages() {
        return super.supportsPartialMessages();
    }

    @SneakyThrows
    @EventListener(MessageEvent.class)
    public void SendClient(MessageEvent event){
        EventVo eventVo = event.getEventVo();
        String sessionId = eventVo.getSessionId();
        ResponseData responseData = (ResponseData) eventVo.getMessage();
        WebSocketSession session = WebSocketSessionManager.getSession(sessionId);
        String answer = "";
        if(0 == responseData.getHeader().get("code").getAsInt()){
            System.out.println("###########");
            if(2 != responseData.getHeader().get("status").getAsInt()){
                System.out.println("****************");
                Payload pl = json.fromJson(responseData.getPayload(),Payload.class);
                JsonArray temp = (JsonArray) pl.getChoices().get("text");
                JsonObject jo = (JsonObject) temp.get(0);
                answer += jo.get("content").getAsString();
            }else {
                Payload pl1 = json.fromJson(responseData.getPayload(),Payload.class);
                JsonObject jsonObject = (JsonObject) pl1.getUsage().get("text");
                int prompt_tokens = jsonObject.get("prompt_tokens").getAsInt();
                JsonArray temp1 = (JsonArray) pl1.getChoices().get("text");
                JsonObject jo = (JsonObject) temp1.get(0);
                answer += jo.get("content").getAsString();
                System.out.println("返回结果为：\n" + answer);
            }
            session.sendMessage(new TextMessage(answer));
        }else{
            session.sendMessage(new TextMessage("返回结果错误：\n" + responseData.getHeader().get("code") +  responseData.getHeader().get("message")));
        }
    }
}
